package ru.ssau.customerManagement.model.db;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.*;

/**
 * Created by illabefat on 20.12.14.
 */
public class DatabaseHelper {
    private static final Logger logger = LoggerFactory.getLogger(DatabaseHelper.class);

    private final String connectionString;
    private final Connection connection;

    public DatabaseHelper(String connectionString)
    {
        this.connectionString = connectionString;
        try {
            Class.forName("oracle.jdbc.OracleDriver");
            connection = DriverManager.getConnection(connectionString);
            logger.info("connection to DB established");
        } catch (ClassNotFoundException e) {
            logger.error("Couldn't init oracle driver", e);
            throw new RuntimeException(e);
        } catch (SQLException e) {
            logger.error("Failed to create conntection", e);
            throw new RuntimeException(e);
        }
    }
    public void executeStatement(String query)
    {
        try {
            logger.info("Performing query '{}'", query);
            Statement statement = connection.createStatement();

            statement.execute(query);
            statement.close();
        } catch (SQLException e) {
            String message = String.format("Failed to execute query '%s'", query);
            logger.error(message, e);
            throw new RuntimeException(message, e);
        }
    }

    public <T> T executeSelect(String query, ResultSetParser<T> parser)
    {
        try {
            logger.info("Performing query '{}'", query);
            Statement statement = connection.createStatement();

            ResultSet resultSet = statement.executeQuery(query);

            T result = parser.parse(resultSet);
            logger.info("Got query result: {}", result);
            statement.close();

            return result;
        } catch (SQLException e) {
            String message = String.format("Failed to execute query '%s'", query);
            logger.error(message, e);
            throw new RuntimeException(message, e);
        }
    }

    public void closeConnection()
    {
        try {
            this.connection.close();
        } catch (SQLException e) {
            logger.error("Failed to close connection");
        }
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        this.closeConnection();
    }
}
